package com.haoxuer.discover.user.service.impl;

import com.haoxuer.discover.config.data.dao.ConfigOptionDao;
import com.haoxuer.discover.user.service.UserTokenService;
import com.haoxuer.discover.user.utils.UserUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.compression.GzipCompressionCodec;
import io.jsonwebtoken.impl.crypto.MacProvider;
import org.apache.shiro.codec.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.Key;
import java.util.Calendar;


@Service
public class UserTokenServiceImpl implements UserTokenService {

  @Autowired
  private ConfigOptionDao optionDao;

  private Logger logger= LoggerFactory.getLogger(UserTokenService.class);

  @Override
  public String token(Long id) {

    String result = "";
    try {
      String key = key();
      Calendar calendar = Calendar.getInstance();
      calendar.add(Calendar.DAY_OF_YEAR, day());
      result = Jwts.builder().setSubject("" + id).signWith(SignatureAlgorithm.HS512, key).setExpiration(calendar.getTime())
          .compressWith(new GzipCompressionCodec()).compact();
    } catch (Exception e) {
      logger.error("生成令牌错误",e);
    }
    return result;
  }

  private String key() {
    String key = optionDao.key("option_token_config");
    if (key == null) {
      Key temp = MacProvider.generateKey();
      key = Base64.encodeToString(temp.getEncoded());
      optionDao.put("option_token_config", key);
    }
    return key;
  }

  private Integer day() {
    String day = optionDao.key("option_token_day");
    if (day == null) {
      day = "360";
      optionDao.put("option_token_day", day);
    }
    return Integer.valueOf(day);
  }

  @Override
  public Long user(String token) {
    Long result = null;
    try {
      if (token == null) {
        throw new UserUtils.TokenInvalidException();
      }
      Jws<Claims> c = Jwts.parser().setSigningKey(key()).parseClaimsJws(token);
      result = Long.parseLong(c.getBody().getSubject());
    } catch (Exception e) {
      logger.error("令牌转化错误",e);
    }
    return result;
  }
}
